package com.ruoyi.business.controller.system;


import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.OSFileStore;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/business/system/info")
public class SystemInformationController {

    @RequestMapping("/getSystemInfo")
    public AjaxResult getSystemInfo() {
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();
        CentralProcessor cpu = hal.getProcessor();
        GlobalMemory memory = hal.getMemory();

        Map<String, Object> data = new HashMap<>();

        // 1. CPU 使用率（1分钟平均负载，0~1）
        double cpuLoad = cpu.getSystemLoadAverage(1)[0] / cpu.getLogicalProcessorCount();
        data.put("cpuUsage", String.format("%.1f%%", cpuLoad * 100));

        // 2. CPU 核心数（物理核心 + 逻辑线程）
        data.put("cpuCores", String.format("%dC/%dT",
                cpu.getPhysicalProcessorCount(),
                cpu.getLogicalProcessorCount()));

        // 3. 系统内存使用（总内存 / 已用内存）
        long totalMemGB = memory.getTotal() / (1024 * 1024 * 1024);
        long usedMemGB = (memory.getTotal() - memory.getAvailable()) / (1024 * 1024 * 1024);
        data.put("memoryUsage", String.format("%dGB/%dGB (%.1f%%)",
                usedMemGB, totalMemGB, (double) usedMemGB / totalMemGB * 100));

        // 4. 磁盘使用率（取第一个磁盘）
        List<OSFileStore> fileStores = si.getOperatingSystem().getFileSystem().getFileStores();
        if (!fileStores.isEmpty()) {
            OSFileStore disk = fileStores.get(0);
            long totalSpaceGB = disk.getTotalSpace() / (1024 * 1024 * 1024);
            long usedSpaceGB = (disk.getTotalSpace() - disk.getUsableSpace()) / (1024 * 1024 * 1024);
            data.put("diskUsage", String.format("%s: %dGB/%dGB (%.1f%%)",
                    disk.getName(), usedSpaceGB, totalSpaceGB,
                    (double) usedSpaceGB / totalSpaceGB * 100));
        }

        // 5. JVM 堆内存（已用 / 最大）
        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        long usedHeapMB = memoryBean.getHeapMemoryUsage().getUsed() / (1024 * 1024);
        long maxHeapMB = memoryBean.getHeapMemoryUsage().getMax() / (1024 * 1024);
        data.put("jvmHeap", String.format("%dMB/%dMB (%.1f%%)",
                usedHeapMB, maxHeapMB, (double) usedHeapMB / maxHeapMB * 100));

        // 6. JVM 线程数（活跃线程）
        data.put("jvmThreads", Thread.activeCount());

        // 7. 系统运行时间（天、小时、分钟）
        long uptime = ManagementFactory.getRuntimeMXBean().getUptime();

// 计算天、小时、分钟
        long days = TimeUnit.MILLISECONDS.toDays(uptime);
        long hours = TimeUnit.MILLISECONDS.toHours(uptime) % 24;
        long minutes = TimeUnit.MILLISECONDS.toMinutes(uptime) % 60;

// 格式化为 "X天X时X分"（始终显示天数）
        String formattedUptime = String.format("%d天%02d时%02d分", days, hours, minutes);

        data.put("uptime", formattedUptime);

        // 8. 操作系统信息
        data.put("osInfo", String.format("%s %s %s",
                System.getProperty("os.name"),
                System.getProperty("os.version"),
                System.getProperty("os.arch")));

        return AjaxResult.success(data);
    }
}